<template>
  <view class="main">
    <view class="search">
      <input type="text" v-model="data.query.orderNo" placeholder="请输入搜索内容" class="search-text" maxlength="30"/>
      <img src="https://img.qumoyugo.com/webimgbg/picopino_icon_search_n.svg" style="width:36rpx;height:36rpx">
    </view>
    <view class="tab_nav">
      <view class="navTitle" v-for="(item,idx) in navData.navList" :key="idx" :class="{ active :navData.isActive === idx}">
        <view class="title_tabs" @click="navData.checked(idx)">
          {{ item.title }}
        </view>
      </view>
    </view>
    <view v-for="(item,idx) in data.list" :key="idx">
      <!-- 活动 -->
      <view class="item" @click="click('/user/order/eventsDetail?orderId='+item.id+'&eventsId='+item.eventsId)" v-if="item.orderType === 0">
        <view class="item_top">
          <view class="item_title">
            {{ item.orderNo }}
            <span class="order_status">{{ data.getOrderStatus(item) }}</span>
          </view>
          <view class="item_main_no">
            <view class="item_main_title u-line-1">{{ item.name }}</view>
            <view class="item_main_time">备注：<span>{{ item.remark }}</span></view>
            <view class="item_main_time time_2">下单时间：<span>{{ item.createdTime }}</span></view>
          </view>
        </view>
        <view class="item_bottom">
          <view>
            订单金额
            <span class="item_price_num">¥ {{ item.orderMoney / 100 }}</span>
          </view>
          <view class="item_bottom_btn_div">
            <button
              class="ordinary_btn plain-g"
              @click.stop="click('/user/order/cancelOrder?isDetail=false&data=' + encodeURIComponent(JSON.stringify(item)))"
              v-if="item.orderStatus === '0'">取消</button>
            <button class="ordinary_btn pay" @click.stop="data.toPay(item)" v-if="item.orderStatus === '0'">支付</button>
            <button class="ordinary_btn plain-g"
                    @click.stop="click('/user/order/cancelOrder?isRefund=true&isDetail=false&data=' + encodeURIComponent(JSON.stringify(item)))"
                    v-if="item.orderStatus === '1' && !item.refundId">退款
            </button>
            <button class="ordinary_btn" @click.stop="review.clickReview(item)"
                    v-if="item.orderStatus==='2' && (!item.evaluateStatus || item.evaluateStatus!=='1')">评价
            </button>
          </view>
        </view>
     </view>
    </view>
    <view v-if="data.list.length<=0" class="empty_icon">
      <image src="https://img.qumoyugo.com/img/default_page_no_order_icon.png"
             style="width: 294rpx;height:330rpx;" mode="aspectFit"/>
    </view>
    <view @click="fabClick" class="contact-plat">
      <image src="https://img.qumoyugo.com/webimgbg/picopino_icon_service-user-center.png" style="width:108rpx;height:108rpx"></image>
    </view>
    <uni-load-more :status="data.status" :icon-size="5" :content-text="data.contentText"
                   v-if="data.list.length > 0"/>
    <uni-popup ref="popup" background-color="#fff" type="bottom">
      <view class="review_popup">
        <view class="startLevel">
          <span>服务满意度：</span>
          <uni-rate size="18" v-model="review.starLevel" disabledColor="#EE751E"/>
        </view>
        <view class="review_content">
          <uni-easyinput autoHeight type="textarea" v-model="review.content" maxlength="255"
                         placeholder="请留下你宝贵的评价"/>
        </view>

        <view class="file_div">
          <view class="upload-img">
            <uni-file-picker limit="9" title="上传图片" @select="successHandler" @delete="deleteHandler"></uni-file-picker>
          </view>
        </view>

        <view class="bottom_div">
          <button class="submitOrder" @click="review.submit">
            发布
          </button>
        </view>
      </view>
    </uni-popup>
    <TipPlain ref="tipPopupPlain" :option="{subTitle: '长按识别联系平台'}">
      <view class="img-code">
        <image src="https://img.qumoyugo.com/webimgbg/picopino_code_feiziy_events.png" style="width: 270rpx;height: 270rpx;" show-menu-by-longpress></image>
      </view>
    </TipPlain>
  </view>
</template>
<script setup>
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, ref } from 'vue'
import { ossConfig } from '@/utils/alioss.js'
import TipPlain from '@/components/popup/plain'
const { $https } = getCurrentInstance().appContext.config.globalProperties
const navData = ref({
  isActive: 0,
  navList: [
    { index: -1, title: '全部' },
    { index: 0, title: '待付款' },
    { index: 1, title: '已付款' },
    { index: 2, title: '已完成' },
    { index: 3, title: '已取消' },
    { index: 9, title: '待评价' }
  ],
  checked: (idx) => {
    data.value.query.page = 1
    navData.value.isActive = idx
    data.value.query.orderStatus = navData.value.navList[idx].index
    uni.showLoading({ title: '加载中' })
    data.value.getList().then(row => {
      uni.hideLoading()
    }).catch(e => uni.hideLoading())
  }
})
const popup = ref()
const tipPopupPlain = ref()
const payWait = ref(false)

const uploadImg = ref([])
const videosList = ref([])
const successHandler = (e) => {
  const len = e.tempFiles.length
  for (let i = 0; i < len; i++) {
    ossConfig(e.tempFiles[i].url).then(res => {
      uploadImg.value.push({
        imageUrl: res,
        uuid: e.tempFiles[i].uuid
      })
    })
  }
}
const deleteHandler = (e) => {
  uploadImg.value = uploadImg.value.filter(item => item.uuid !== e.tempFile.uuid)
}

const review = ref({
  starLevel: 0,
  content: '',
  orderType: null,
  orderId: null,
  clickReview: (item) => {
    popup.value.open()
    review.value.orderType = item.orderType
    review.value.orderId = item.id
    review.value.starLevel = 0
    review.value.content = ''
  },
  submit: () => {
    if (!review.value.content) {
      uni.showToast({ title: '请输入评价', icon: 'none' })
      return
    }
    if (!review.value.starLevel || review.value.starLevel <= 0) {
      uni.showToast({ title: '请选择评分', icon: 'none' })
      return
    }
    uni.showLoading({ title: '加载中' })
    if (videosList.value.length > 0) {
      console.log('暂不支持上传视频')
    } else {
      const params = {
        reviewParams: JSON.stringify({
          starLevel: review.value.starLevel,
          content: review.value.content,
          reviewImg: uploadImg.value,
          reviewType: review.value.orderType,
          orderId: review.value.orderId
        })
      }
      $https({
        url: '/sensitive/check',
        type: '',
        method: 'post',
        data: {
          title: '',
          description: review.value.content
        }
      }).then(res => {
        $https({
          url: '/app/order/reviewOrder',
          type: '',
          method: 'post',
          data: params
        }).then(res => {
          uni.hideLoading()
          if (res.code === 0) {
            uni.showToast({ title: '操作成功', icon: 'none' })
            setTimeout(() => {
              popup.value.close()
              data.value.getList()
            }, 1000)
          }
        }).catch(c => uni.hideLoading())
      }).catch(c => uni.hideLoading())
    }
  }
})

onShow(() => {
  data.value.query.page = 1
  data.value.getList()
  payWait.value = false
})

onLoad((options) => {
  navData.value.isActive = Number(options.orderStatus) || 0
  data.value.query.orderStatus = navData.value.navList[navData.value.isActive].index
})

const data = ref({
  query: {
    page: 1,
    pageSize: 10,
    orderNo: '',
    orderStatus: -1
  },
  list: [],
  total: 0,
  status: 'more',
  contentText: {
    contentdown: '上拉加载更多~',
    contentrefresh: '加载中',
    contentnomore: '我是有底线的~'
  },
  getList: (isLoading = true) => {
    return new Promise((resolve, reject) => {
      $https({
        url: '/app/order/page/list',
        type: '',
        method: 'get',
        data: data.value.query
      }).then(res => {
        payWait.value = false
        if (res.code === 0) {
          data.value.list = isLoading ? res.data.items : data.value.list.concat(res.data.items)
          data.value.total = res.data.pagination.total_record
          if (data.value.list.length >= data.value.total) {
            data.value.status = 'no-more'
          }
        }
        resolve()
      }).catch(e => {
        payWait.value = false
        reject(e)
      })
    })
  },
  getOrderStatus: (item) => {
    const eventOrderList = ['待支付', '已支付', '已完成', '已取消', '已退款']
    switch (item.orderType) {
      case 0:
        return eventOrderList[item.orderStatus]
    }
  },
  search: () => {
    data.value.query.page = 1
    uni.showLoading({ title: '加载中' })
    data.value.getList().then(row => {
      uni.hideLoading()
    }).catch(e => uni.hideLoading())
  },
  toPay: (item) => {
    if (payWait.value) {
      return
    }
    payWait.value = true
    if (item.orderType === 2 || !item.couponMoney) {
      const data = {
        tableId: item.id,
        orderType: item.orderType
      }
      payJump(data)
      return
    }
    if (item.couponMoney / 100 <= item.orderMoney) {
      const data = {
        tableId: item.id,
        orderType: item.orderType
      }
      payJump(data)
    } else {
      const params = {
        orderType: item.orderType,
        orderId: item.id
      }
      $https({
        url: '/app/order/orderPay',
        type: '',
        method: 'post',
        data: params
      }).then(res => {
        if (res.code === 0) {
          uni.showToast({ title: '操作成功', icon: 'none' })
          data.value.getList()
          setTimeout(() => {
            uni.hideToast()
          }, 1000)
        } else {
          payWait.value = false
        }
      }).catch(e => {
        payWait.value = false
      })
    }
  }
})
// 调起支付
const payJump = async order => {
  $https({
    url: '/app/order/pay',
    type: '',
    method: 'POST',
    data: {
      orderId: order.tableId,
      orderType: order.orderType
    }
  })
    .then(res => {
      if (res.code === 0) {
        $https({
          url: '/pay/query',
          type: 'public',
          data: {
            uuid: res.data.payOrder.uuid,
            openClientType: 'MP',
            pay: true
          }
        })
          .then(res1 => {
            if (res1.code === 0) {
              if (!res1.data.payWayList[0]) {
                uni.hideLoading()
                uni.showToast({ title: '收银台返回数据不正确' })
                return false
              }
              uni.login({
                success: reslogin => {
                  $https({
                    url: '/order/pay',
                    type: 'public',
                    method: 'POST',
                    data: {
                      payWayId: res1.data.payWayList[0].id,
                      uuid: res.data.payOrder.uuid,
                      scene: 'mp4',
                      wxCode: reslogin.code,
                      pay: true
                    }
                  })
                    .then(res2 => {
                      payWait.value = false
                      if (res2.code === 0) {
                        uni.requestPayment({
                          ...res2.data.signParam,
                          success: res => {
                            if (order.orderType === 1) {
                              // 支付成功需询问用户是否订阅消息
                              uni.requestSubscribeMessage({
                                tmplIds: ['famjs1y0aFN5I8uha7rhrIhTJE4o34cqY78wOZUk7X0'],
                                success: function (res) {
                                  wx.login({
                                    success: (loginRes) => {
                                      $https({
                                        // 利用code去换取openid
                                        url: '/js-token',
                                        type: '',
                                        data: {
                                          code: loginRes.code,
                                          scene: 'mp4'
                                        }
                                      }).then(resOpenid => {
                                        if (resOpenid.code === 0) {
                                          $https({
                                            // 添加订阅
                                            url: '/subscribe/add',
                                            type: '',
                                            method: 'POST',
                                            data: {
                                              templateId: ['famjs1y0aFN5I8uha7rhrIhTJE4o34cqY78wOZUk7X0'],
                                              openId: resOpenid.data.openid
                                            }
                                          }).then((addRes) => {
                                            if (addRes.code === 0) {
                                              data.value.getList()
                                              uni.hideLoading()
                                            }
                                          })
                                        }
                                      })
                                    },
                                    fail (res) {
                                      data.value.getList()
                                      uni.hideLoading()
                                    }
                                  })
                                },
                                fail: function (res) {
                                  data.value.getList()
                                  uni.hideLoading()
                                }
                              })
                            } else {
                              data.value.getList()
                              uni.hideLoading()
                            }
                          },
                          fail: () => {
                            uni.showToast({ title: '支付失败', icon: 'error' })
                            data.value.getList()
                            uni.hideLoading()
                          }
                        })
                      } else {
                        uni.hideLoading()
                      }
                    })
                    .catch(e => {
                      payWait.value = false
                      uni.hideLoading()
                    })
                },
                fail: () => {
                  uni.hideLoading()
                }
              })
            } else {
              payWait.value = false
              uni.hideLoading()
            }
          })
          .catch(e => {
            payWait.value = false
            uni.hideLoading()
          })
          // location.replace(res.data.jumpUrl + '&clientType=H5&orgin=cash')
      } else {
        payWait.value = false
        uni.hideLoading()
      }
    })
    .catch(e => {
      payWait.value = false
      uni.hideLoading()
    })
}
const click = (url) => {
  uni.navigateTo({
    url
  })
}

// 下拉刷新
onPullDownRefresh(() => {
  data.value.query.page = 1
  data.value.getList().then(row => {
    uni.stopPullDownRefresh()
  }).catch(e => uni.stopPullDownRefresh())
})
const fabClick = () => {
  tipPopupPlain.value.show()
}
// 上拉加载
onReachBottom(() => {
  if (data.value.total > data.value.list.length) {
    data.value.status = 'loading'
    data.value.query.page += 1
    data.value.getList(false).then(row => {
      data.value.status = 'more'
    })
  } else {
    data.value.status = 'no-more'
  }
})
</script>
<style scoped lang="scss">
@import "@/assets/styles/minx.scss";
.main {
  min-height: 100vh;
  background-color: #FFF8F0;
  padding: 40rpx 30rpx calc(env(safe-area-inset-bottom)) 30rpx;
}

.search {
  display: flex;
  height: 90rpx;
  border-radius: 20rpx;
  background: white;
  align-items: center;
  border: 1px solid #737373;
  color: #414141;
  padding: 0 40rpx;
  justify-content: space-between;
  margin-bottom: 40rpx;
}
.search-text {
  flex: 1;
}
.tab_nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 40rpx;
}

.tab_nav .navTitle {
  height: 42rpx;
  line-height: 32rpx;
  text-align: center;
  font-size: 32rpx;
  color: #414141;
  font-weight: bold;
  position: relative;
  &.active{
    color: #000;
    &::after{
      content: "";
      position: absolute;
      height: 14rpx;
      border-radius: 100px;
      background: #F39A41;
      left: 0;
      right: 0;
      bottom: 2rpx;
    }
  }
}
.title_tabs {
  position: relative;
  z-index: 100;
}

.item_bottom {
  padding-top: 30rpx;
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #414141;
  position: relative;
  margin-top: 30rpx;
  &::before{
    @include border(top, #E1E1E1)
  }
}

.item_price_num {
  font-size: 35rpx;
  font-weight: 500;
  color: #EE751E;
  margin-left: 20rpx;
}

.item {
  background: #FFFFFF;
  border-radius: 20rpx;
  margin-top: 20rpx;
  padding: 30rpx;
}

.item_title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #000;
  position: relative;
  padding-bottom: 20rpx;
  justify-content: space-between;
  font-weight: bold;
  &::before{
    @include border(bottom, #E1E1E1)
  }
}

.order_status {
  font-size: 28rpx;
  color: #737373;
  font-weight: normal;
}

.item_main_no {
  margin-top: 30rpx;
}

.item_main {
  margin-top: 45rpx;
  display: flex;
  align-items: center;
}

.main_img {
  width: 170rpx;
  height: 170rpx;
  margin-right: 36rpx;
}

.item_main_title {
  font-size: 28rpx;
  font-weight: bold;
  color: #414141;
  margin-bottom: 20rpx;
  line-height: 32rpx;
}

.item_main_time {
  font-size: 24rpx;
  font-weight: 400;
  color: #737373;
  line-height: 24rpx
}

.item_main_time > span {
  color: black;
}

.time_2 {
  margin-top: 14rpx;
}

.ordinary_btn {
  background: #FFFFFF;
  border: 1px solid rgba(238,117,30,0.6);
  border-radius: 28rpx;
  font-size: 22rpx;
  color: #EE751E;
  width: 140rpx;
  &.plain-g{
    color: #999;
    border-color: rgba(153,152,153,0.6);
  }
  &.pay{
    background: #EE751E;
    color: #fff;
  }
}

.item_bottom_btn_div {
  margin-left: auto;
  display: flex;
}

.item_bottom_btn_div > button {
  margin-right: 20rpx;
}

.item_bottom_btn_div > button:last-child {
  margin-right: 0;
}

.empty_icon {
  text-align: center;
  //margin-top: calc(50% - 244rpx);
  margin-top: 50%;
}

.startLevel {
  font-size: 29rpx;
  font-weight: 500;
  color: #333333;
  line-height: 14rpx;
  display: flex;
  align-items: center;
}

.review_popup {
  padding: 45rpx 47rpx 0;
  max-height: 60%;
}

.bottom_div {
  margin-top: 40rpx;
  width: 100%;
  padding-bottom: calc(env(safe-area-inset-bottom) + 22rpx);
}

.submitOrder {
  width: 444rpx;
  height: 90rpx;
  background: #525FA2;
  border-radius: 45rpx;
  font-weight: 500;
  color: #FFFFFF;
  line-height: 90rpx;
  font-size: 32rpx;
}

.review_content {
  margin-top: 45rpx;
  display: flex;
  align-items: center;
}

.review_main_img {
  width: 56.94rpx;
  height: 60.42rpx;
  margin-left: 18rpx;
}

.file_div {
  margin-top: 40rpx;
  max-height: 200px;
  overflow: auto;
}

.header-uploader {
  margin-bottom: 60rpx;
  padding-top: 24rpx;
}

.uploader-input-box {
  border-radius: 12rpx;
  color: #999999;
  font-size: 26rpx;
  height: 127.78rpx;
  width: 127.78rpx;
}

.uploader-input {
  height: 228rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.uploader__img {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  position: relative;

  .icon {
    width: 58rpx;
    height: 66rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 3;
  }

  .close {
    width: 36rpx;
    height: 36rpx;
    position: absolute;
    top: 6rpx;
    right: 6rpx;
    z-index: 4;
  }

  .pc {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .video {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
  }

  .tips {
    width: 142rpx;
    background: #000000;
    opacity: 0.5;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 24rpx;
    line-height: 24rpx;
    padding: 12rpx 0;
    text-align: center;
    color: #ffffff;
    border-radius: 12rpx;
  }

  .img-sw {
    width: 100%;
    height: 100%;
  }
}

.img-sw {
  width: 100%;
  height: 100%;
}

.address_txt {
  font-size: 29rpx;
  font-weight: 500;
  color: #525FA2;
  line-height: 14rpx;
}

.arrows2_icon {
  width: 43.06rpx;
  height: 18.06rpx;
  margin: 0 20rpx;
}

.date_div > view {
  margin-left: 25rpx;
  border-radius: 18rpx;
  background: #F1F1F1;
  text-align: center;
  padding: 27rpx;
  display: inline-block;
}

.date_div > view > view {
  font-size: 24rpx;
  font-weight: 500;
  color: #999999;
}

.date_div > view:first-child {
  margin-left: 0;
}

.date_div, .time_div {
  overflow-y: auto;
  width: 100%;
  white-space: nowrap;
  display: flex;
}

.optionalTime {
  font-size: 24rpx;
  font-weight: 500;
  color: #999999;
}

.isSelectDate, .selectTime {
  background: #FFEADB !important;
}

.isSelectDate > view > view, .selectTime > view {
  color: #333333 !important;
}

.isDisable {
  opacity: 0.5 !important;
}

.review_popup_title {
  text-align: center;
  margin-bottom: 32rpx;
  font-size: 29rpx;
  font-weight: 500;
  color: #333333;
}

.time_div {
  margin-top: 64rpx;
}

.time_div > view:first-child {
  margin-left: 0;
}

.time_div > view {
  margin-left: 25rpx;
  border-radius: 18rpx;
  background: #F1F1F1;
  text-align: center;
  display: inline-block;
  font-size: 24rpx;
  font-weight: 500;
  color: #999999;
  padding: 21rpx 30rpx;
  height: 110rpx;
  color: #333333;
}
.contact-plat{
  width: 108rpx;
  height: 108rpx;
  position: fixed;
  bottom: calc(90rpx + env(safe-area-inset-bottom));
  right: 30rpx;
  z-index: 99;
}
.img-code{
  width: 270rpx;
  height: 270rpx;
  margin: 20rpx auto;
}
.time_div > view > view:first-child {
  margin-left: 0;
}
</style>
<style scoped>
/deep/ .uni-grid-item {
  width: 100% !important;
}

/deep/ .uni-searchbar__box {
  background: white !important;
}

/deep/ .is-add {
  width: 128 rpx !important;
  height: 128 rpx !important;
  border-radius: 18 rpx !important;
}

/deep/ .uni-popup .uni-popup__wrapper {
  max-height: 60%;
  overflow: auto;
}

/deep/ .uni-easyinput__content-input {
  background: #F0F0F0 !important;
}
</style>
